package router

import (
	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"net/http"
	"web_api_gogf/app/api"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

// 允许跨域请求中间件
func MiddlewareCORS(r *ghttp.Request) {
	corsOptions := r.Response.DefaultCORSOptions()
	//corsOptions.AllowDomain = []string{"goframe.org", "johng.cn"}
	//corsOptions.AllowHeaders = "Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,X-Forwarded-*,Pragma,Cache-Control,If-Modified-Since,userToken,appid"
	r.Response.CORS(corsOptions)
	r.Middleware.Next()
}

//用户认证中间件
func MiddlewareAuth(r *ghttp.Request) {
	//排除路径
	array := garray.NewFrom(g.Slice{"/admin/login/account"})
	if array.Contains(r.RequestURI) == false {
		userData, err := service.SysUser.AuthorizationGetUserData(r)
		if err != nil {
			r.Response.WriteStatus(http.StatusForbidden)
			response.JsonExit(r, 10000, err.Error())
		}
		if userData == nil {
			r.Response.WriteStatus(http.StatusUnauthorized)
			response.JsonExit(r, 10000, "用户不存在")
		}
	}
	// 中间件处理逻辑
	r.Middleware.Next()
}
func init() {
	s := g.Server()
	s.BindHandler("GET:/", func(r *ghttp.Request) {
		r.Response.Write("<div style='text-align: center;'>欢迎进入首页！</div>")
	})
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.ALL("/hello", api.Hello)
	})
	s.Group("/admin/", func(group *ghttp.RouterGroup) {
		//跨域设置,权限中间件
		group.Middleware(MiddlewareCORS, MiddlewareAuth)
		group.POST("/login", api.Login)

		group.Group("/", func(group *ghttp.RouterGroup) {
			group.ALL("/user", api.User)
			group.ALL("/sys-menu-group", api.SysMenuGroup)
			group.ALL("/sys-menu", api.SysMenu)
			group.ALL("/sys-permission", api.SysPermission)
			group.ALL("/sys-role", api.SysRole)
			group.ALL("/sys-user", api.SysUser)
		})

	})
}
